import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './mutation-types'
import Bus from '@/utils/Bus'
import CNST from '@/utils/constant'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    areaId: '',
    user: {
      userType: '', // 用户类型
      userId: '', // 用户id
      userName: '', // 用户名称
      mobilePhone: '', // 用户手机号
      superAdmin: '', //  是否为超级 管理员
      permissions: [], // 权限数组
      currentPath: '' // 当前的路由
    }
  },
  mutations: {
    [types.SET_AREAID] (state, id) {
      state.areaId = id
      Bus.$emit(CNST.UPDATE_TIME_STAMP)
    },
    [types.SET_USER] (state, data) {
      // 匹配路由权限
      state.user.userType = data.userType // 用户类型
      state.user.userId = data.userId // 用户Id
      state.user.userName = data.userName // 用户姓名
      state.user.mobilePhone = data.mobilePhone // 用户手机号
      state.user.superAdmin = data.superAdmin // 是否为超级管理员
      state.user.permissions = data.permissions // 权限数组

      localStorage.setItem('user', JSON.stringify(state.user))

      // 设置cookie  失效期30分钟
      let exp = new Date()
      exp.setTime(exp.getTime() + 1000 * 60 * 30)
      document.cookie = `user=${data.token};expires=${exp.toUTCString()};path=/`
    },
    [types.UPDATE_USER] (state, data) {
      state.user.userType = data.userType
      state.user.userId = data.userId
      state.user.userName = data.userName
      state.user.mobilePhone = data.mobilePhone
      state.user.superAdmin = data.superAdmin
      state.user.currentPath = data.currentPath

      localStorage.setItem('user', JSON.stringify(data))
    },
    [types.DEL_USER] (state) {
      state.user = {
        userType: '', // 用户类型
        userId: '', // 用户id
        userName: '', // 用户名称
        mobilePhone: '', // 用户手机号
        superAdmin: false // 是否为超级管理员
      }
      localStorage.removeItem('user')
      let delexp = new Date()
      delexp.setTime(delexp.getTime() - 1)
      document.cookie = `user=;expires=${delexp.toUTCString()};path=/`// 清除cookie
    }
  },
  actions: {
    [types.SET_USER] ({ commit }, data) {
      commit(types.SET_USER, data)
    },
    // 设置token
    [types.UPDATE_USER] ({ commit }, data) {
      commit(types.UPDATE_USER, data)
    }
  }
})
